//
//  KYUserAccountModel.swift
//  01-我的微博
//
//  Created by apple on 15/7/31.
//  Copyright © 2015年 KY. All rights reserved.
//

import UIKit

class KYUserAccountModel: NSObject, NSCoding {
    
    
    
    class var userLogon: Bool {
        return loadAccount() != nil
    }
    
    /// 用于调用access_token，接口获取授权后的access token
    var access_token :String?
    /// access_token的生命周期，单位是秒数
    var expires_in : NSTimeInterval = 0 {
        didSet{
            expiresDate = NSDate(timeIntervalSinceNow: expires_in)
        }
    }
    /// 当前授权用户的UID
    var uid : String?
    /// 过期日期
    var expiresDate : NSDate?
    
    /// 友好显示名称
    var name: String?
    /// 用户头像地址（大图），180×180像素
    var avatar_large: String?
    
    //MARK: - 字典转模型
    // kvc 赋值
    init(dict: [String: AnyObject]) {
        super.init()
        
        /// 此处要注意将数据保存 -- 易错
        KYUserAccountModel.userAccount = self
        
        self.setValuesForKeysWithDictionary(dict)
    }
    
    override func setValue(value: AnyObject?, forUndefinedKey key: String) {}
    
    /// 对象描述信息
    override var description: String {
        
        let dict = ["access_token", "expires_in", "uid", "expiresDate", "name", "avatar_large"]
        return  "\(dictionaryWithValuesForKeys(dict))"
    }
    
    // MARK: - 加载用户信息
    func loadUserInfo(finashed: (error: NSError?) -> ()){
    
        KYNetworkTools.sharedNetworkTools.loadUserInfo(uid!) { (result, error) -> () in
            if error != nil {
                // 错误上传
                finashed(error: error)
                return
            }
            // 设置用户信息
            self.name = result!["name"] as? String
            self.avatar_large = result!["avatar_large"] as? String
            
            // 保存用户信息
            self.saveAccount()
            // 没有出错同样上传
            finashed(error: nil)
        }
    
    }
    
    
    
    // MARK: - 归档&解档
    // 保存归档文件
    static private let accountPath = (NSSearchPathForDirectoriesInDomains(NSSearchPathDirectory.DocumentDirectory, NSSearchPathDomainMask.UserDomainMask, true).last! as NSString).stringByAppendingPathComponent("account.plist")
    
    /// 保存用户账号
    func saveAccount() {
        NSKeyedArchiver.archiveRootObject(self, toFile: KYUserAccountModel.accountPath)
    }
    
    
    /// 创建静态账户 防止经常调用 形成混乱
    private static var userAccount: KYUserAccountModel?
    /// 加载用户账号
    class func loadAccount() -> KYUserAccountModel? {
        
        // 判断账号是否存在
        if userAccount == nil {
            userAccount = NSKeyedUnarchiver.unarchiveObjectWithFile(accountPath) as? KYUserAccountModel
        }
        // 判断是否过期
        if let date = userAccount?.expiresDate where date.compare(NSDate()) == NSComparisonResult.OrderedAscending {
            userAccount = nil
        }
        return userAccount
    }
    
    /// 归档 保存 - 将对象转换为二进制 放进磁盘
    func encodeWithCoder(aCoder: NSCoder) {
        aCoder.encodeObject(access_token, forKey:"access_token")
        aCoder.encodeDouble(expires_in, forKey: "expires_in")
        aCoder.encodeObject(expiresDate, forKey:"expiresDate")
        aCoder.encodeObject(uid, forKey: "uid")
        aCoder.encodeObject(name, forKey: "name")
        aCoder.encodeObject(avatar_large, forKey: "avatar_large")
    }
    
    /// 解档 恢复 - 将二进制数据转换为对象
    required init?(coder aDecoder: NSCoder) {
        access_token = aDecoder.decodeObjectForKey("access_token") as? String
        expires_in = aDecoder.decodeDoubleForKey("expires_in")
        expiresDate = aDecoder.decodeObjectForKey("expiresDate") as? NSDate
        uid = aDecoder.decodeObjectForKey("uid") as? String
        name = aDecoder.decodeObjectForKey("name") as? String
        avatar_large = aDecoder.decodeObjectForKey("avatar_large") as? String
    }
    
    
}
